package his.util;
import java.sql.*;

public class JDBC_util {

	//1��������
	static{
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	//2��������Э��URL����������
	public static Connection getconnection(){
		String url="jdbc:mysql://localhost:3306/webstudy?useUnicode=true&amp;characterEncoding=UTF-8;autoReconnect=true&useSSL=false";
		Connection con = null;
		try {
			con = DriverManager.getConnection(url, "root", "123456");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con;
	}
		
	//3��������
	public static void printresultset(ResultSet rs){
		if(rs!=null){
			try {
				ResultSetMetaData rm=rs.getMetaData();
				int num=rm.getColumnCount();
				StringBuffer sb=new StringBuffer();
				for(int i=1;i<=num;i++){
					int size=rm.getColumnDisplaySize(i);
					String colval=rm.getColumnName(i);
					if(colval==null) colval="null";
					int b=(size-colval.length())/2;
					if(b>0){
						for(int j=0;j<b;j++)sb.append(" ");
						sb.append(colval);
						for(int j=0;j<b;j++)sb.append(" ");
						if((size-colval.length())%2!=0){
							sb.append(" ");
						}
					}else{
						sb.append(colval.substring(0,size));
					}
				}
				sb.append("\n");
				while(rs.next()){
					for(int i=1;i<=num;i++){
						int size=rm.getColumnDisplaySize(i);
						String val=rs.getString(i);
						if(val==null) val="null";
						int b=(size-val.length())/2;
						if(b>0){
							for(int j=0;j<b;j++)sb.append(" ");
							sb.append(val);
							for(int j=0;j<b;j++)sb.append(" ");
							if((size-val.length())%2!=0){
								sb.append(" ");
							}
						}else{
							sb.append(val.substring(0,size));
						}
					}
					sb.append("\n");
				}
				System.out.println(sb.toString());
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	//4.�ͷ���Դ
	public static void release(Connection con,Statement stmt,ResultSet rs){
		if(rs!=null)
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		if(stmt!=null)
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		if(con!=null)
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	//�ύ����
	public static void commitTransaction(Connection con){ 
		try {
			con.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	//�ع�����
	public static void rollbackTransaction(Connection con){
		try {
			con.rollback();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	//�ֶ��������
	public static void setAutoCommit(Connection con){
		try {
			con.setAutoCommit(false);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
